﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using DevExpress.Web.Mvc;
using System.Data;
using ElingOA6_Admin_DSJCJ.Models;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 用品管理
    /// </summary>
    /// 
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class OfficeItemManagerController : AdminBaseController
    {
        //
        // GET: /Admin/OfficeItemManager/
        /// <summary>
        /// 用品管理主页
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_OfficeItemManager", Order = 1)]
        [LogPageActionFilter("用品管理", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 数据列表
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult OfficeItemManagerList(string itemClsNo)
        {
            
            int pageIndex = 1;
            List<Model.Item> itemList = GetItemList(pageIndex);
            if (itemClsNo == null)
            {
                ViewData["itemClsNo"] = "00";
            }
            else
            {
                ViewData["itemClsNo"] = itemClsNo;
            }

            List<Model.ItemCls> itemClsModel = CommonCode.GetItemList(GlobalConstant.ENTITYNO);
            List<SelectListItem> list = new List<SelectListItem>();
            SelectListItem item = new SelectListItem();
            item.Text = "全部";
            item.Value = "00";
            list.Add(item);
            foreach (Model.ItemCls itemCls in itemClsModel)
            {
                item = new SelectListItem();
                item.Text = itemCls.FItemClsName;
                item.Value = itemCls.FItemClsNo;
                list.Add(item);
            }

            ViewData["clsNoList"] = list;



            return View(itemList);
        }


        /// <summary>
        /// 用于刷新
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult OfficeItemManagerListPartial()
        {

            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            string itemClsNo = Request.Params["itemClsNo"];

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }


            List<Model.Item> itemList = GetItemList(pageIndex, pageCount, pageRowSize);


            return PartialView("OfficeItemManagerListPartial", itemList);
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageCount">每页显示大小</param>
        /// <param name="pageRowSize">每页显示页数</param>
        /// <returns>集合</returns>
        private List<Model.Item> GetItemList(int pageIndex, int pageCount = 0, int pageRowSize = 0)
        {
            BLL.Item itemBll = new BLL.Item();

            BLL.Common commonBll = new BLL.Common();
            string fiedls = "*";
            int total;

            string itemClsNo = Request.Params["itemClsNo"];
            string where = "";
            if (itemClsNo != null)
            {
                if (itemClsNo == "00")
                {
                    where = "";
                }
                else
                {
                    where = " FItemClsNo= " + itemClsNo;
                }
            }
            
            DataSet ds = commonBll.GetListByPage("dbo.v_Item_Cls", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, where, "FItemNo", 0, out total);

            List<Model.Item> itemAllList = new List<Model.Item>();
            List<Model.Item> itemList = itemBll.DataTableToListItem(ds.Tables[0]);

            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                itemAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (itemList.Count > i)
                {
                    itemAllList[((pageIndex - 1) * pageRowSize) + i] = itemList[i];
                }
            }

            return itemAllList;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult OfficeItemManagerEdit(string itemNo)
        {
            Model.Item itemModel = new Model.Item();

            if (string.IsNullOrEmpty(itemNo))
            {
                ViewData["itemClsNo"] = "00";
                ViewData["type"] = "ADD";
                ViewData["itemNo"] = true;
            }
            else
            {
                ViewData["type"] = "Edit";
                ViewData["itemNo"] = false;
                BLL.Item itemBll = new BLL.Item();
                itemNo = Fetch.estimateString(itemNo, CheckGetEnum.Safety);
                string entityNo = GlobalConstant.ENTITYNO;
                itemModel = itemBll.GetModel(itemNo, entityNo);
                ViewData["itemClsNo"] = itemModel.FItemClsNo;
            }

            List<Model.ItemCls> itemClsModel = CommonCode.GetItemList(GlobalConstant.ENTITYNO);
            List<SelectListItem> list = new List<SelectListItem>();
            SelectListItem item = new SelectListItem();
            item.Text = "请选择一种类别";
            item.Value = "00";
            list.Add(item);
            foreach (Model.ItemCls itemCls in itemClsModel) {
                item = new SelectListItem();
                item.Text = itemCls.FItemClsName;
                item.Value = itemCls.FItemClsNo;
                list.Add(item);
            }

            ViewData["clsNoList"] = list;

            return View(itemModel);
        
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="itemModel">itemModel对象</param>
        /// <returns>视图</returns>
        public ActionResult Save(Model.Item itemModel)
        {
            itemModel.FEntityNo = GlobalConstant.ENTITYNO;
            itemModel.FIsUse = CheckBoxExtension.GetValue<bool>("FIsUse") == true ? "Y" : "N";
            itemModel.FItemClsNo = ComboBoxExtension.GetValue<string>("FItemClsName");
            itemModel.FItemNo = Fetch.Post("FItemNo");
            itemModel.FItemName = Fetch.Post("FItemName");
            itemModel.FItemSpec = Fetch.Post("FItemSpec");
            itemModel.FSafetyStock = decimal.Parse(Fetch.Post("FSafetyStock"));
            itemModel.FUnit = Fetch.Post("FUnit");

            string type = Fetch.Post("hdtype");
            BLL.Item itemBll = new BLL.Item();


            BLL.ItemYearBal itemYearBalBll = new BLL.ItemYearBal();
            Model.ItemYearBal itemYearBalModel = new Model.ItemYearBal();

            itemYearBalModel.FYear = DateTime.Now.Year;
            itemYearBalModel.FItemNo = Fetch.Post("FItemNo");
            itemYearBalModel.FEntityNo = GlobalConstant.ENTITYNO;

            string entityNo = GlobalConstant.ENTITYNO;
            try {
                if (type == "ADD")
                {
                    //if (itemBll.Exists(itemModel.FItemNo, entityNo))
                    //{
                    //    ViewData["itemNo"] = true;
                    //    ViewData["message"] = "message1";
                    //    ViewData["itemClsNo"] = itemModel.FItemClsNo;
                    //    //Response.Write("<script>alert('用品编号不能重复输入，请重新输入!');</script>");
                    //    //Response.Flush();
                    //    //Response.End();
                    //}
                    //else
                    //{
                    //    if (itemModel.FItemClsNo == "00")
                    //    {
                    //        ViewData["itemNo"] = true;
                    //        ViewData["message"] = "message2";
                    //        ViewData["itemClsNo"] = itemModel.FItemClsNo;
                    //        //Response.Write("<script>alert('请选择一种类别!');</script>");
                    //        //Response.Flush();
                    //        //Response.End();                            
                    //    }
                    //    else
                    //    {
                    itemBll.Add(itemModel, itemYearBalModel);
                    //itemYearBalBll.Add(itemYearBalModel);
                    ViewData["jsAlert"] = "增加保存成功!";
                    ViewData["itemNo"] = true;
                    //}
                       
                    //}
                }
                else if (type == "Edit")
                {
                    itemBll.Update(itemModel);
                    ViewData["jsAlert"] = "修改保存成功!";
                    ViewData["itemNo"] = false;
                    
                }
                
            }
            catch(Exception) {
                ViewData["jsAlert"] = "操作失败!";
                ViewData["itemNo"] = true;
            }

            return View("OfficeItemManagerEdit", itemModel);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="itemNos">编号</param>
        /// <returns>返回字符判断是否删除</returns>
        public string DeleteManyItem(string itemNos)
        {
            string str = "";
            string entityNo = GlobalConstant.ENTITYNO;

            string[] itemArray = itemNos.Split(new string[] { "%!^" }, StringSplitOptions.RemoveEmptyEntries);
            BLL.Item itemBll = new BLL.Item();
            string year = DateTime.Now.Year.ToString();
            try {
                ///如果有领用则无法删除该项纪录
                //if (1 == 1)
                //{
                //    str = "exists";
                //}
                //else
                //{
                itemBll.DelManyItem(itemArray, entityNo, year);
                    str = "ok";
                //}
            }
            catch (Exception)
            {
                str = "error";
            }
            return str;
        
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="itemNo">编号</param>
        /// <returns>返回字符判断是否删除</returns>
        public string DeleteItem(string itemNo)
        {
            string str = "";
            string entityNo = GlobalConstant.ENTITYNO;
            string year = DateTime.Now.Year.ToString();
            BLL.Item itemBll = new BLL.Item();
            try {
                ///如果有领用则无法删除该项纪录
                //if (1 == 1)
                //{
                //    str = "exists";
                //}
                //else
                //{
                itemBll.Delete(itemNo, entityNo, year);
                str = "ok";
                //}
            }
            catch (Exception)
            {
                str = "error";
            }

            return str;
        }

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="itemNo"></param>
        /// <returns></returns>
        public string Exists(string itemNo) {
            string str = "";
            string entityNo = GlobalConstant.ENTITYNO;
            BLL.Item itemBll = new BLL.Item();
            if (itemBll.Exists(itemNo, entityNo))
            {
                str = "exist";
            }

            return str;
        }

    }
}
